﻿#include "stdafx_logm.h"
namespace LOGM
{
	//class level var initialization
	LogSave *LogSave::_instance = 0;
	QTextStream *LogSave::log_Out = new QTextStream();
	QString *LogSave::log_line_message = new QString();
	 
	LogSave::LogSave()
	{
		this->openLogFile();
		this->installMessageHandler();
	}
	//creat single instance
	LogSave *LogSave::instance()
	{
		if(!LogSave::_instance)
			LogSave::_instance = new LogSave;
		return LogSave::_instance;
	}
	

	LogSave::~LogSave()
	{
		if(nullptr != log_File){
			log_File->flush();
			log_File->close();
			delete log_File;
			
			log_File = nullptr;
		}
	}


	void LogSave::openLogFile()
	{
		log_Dir.setPath("qt_log");	 
		openLogDir();
		logFIleCreatedDate = QDate::currentDate();
		logFIleCreatedTime = QTime::currentTime();
		QString Log_Path_DateTime = log_Dir.absoluteFilePath(logFIleCreatedDate.toString("yyyy-MM-dd_")
														   + logFIleCreatedTime.toString("hh_mm_ss_zzz.log"));

		log_File = new QFile(Log_Path_DateTime);//construte file name by using time stamp
		log_Out = (log_File->open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Append)) ?  new QTextStream(log_File) : nullptr;
		std::cout << logFIleCreatedDateTime.toString("yyyy-MM-dd hh:mm:ss.zzz").toStdString() << std::endl;

	}

	void LogSave::closeLogFile()
	{
		log_File->flush();
		log_File->close();
		delete log_File;
	}

	void LogSave::openLogDir()
	{
		if(!log_Dir.exists()){
			log_Dir.mkpath(".");
		}
	}

	
	void logMessageHandler(QtMsgType log_type, const char *msg)
	{
		static QMutex log_mutex;
		log_mutex.lock();

		QString log_msg_text;
		switch(log_type)
		{
		case QtDebugMsg:
			log_msg_text = QString("Debug:%1").arg(msg);
			break;

		case QtWarningMsg:
			log_msg_text = QString("Warning:%1").arg(msg);
			break;

		case QtCriticalMsg:
			log_msg_text = QString("Critical:%1").arg(msg);
			break;

		case QtFatalMsg:
			log_msg_text = QString("Fatal:%1").arg(msg);
			abort();
		}

		*LogSave::log_Out << QString("[DataTime:%1] %2").arg(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz")).arg(log_msg_text) << endl;
		LogSave::instance()->logText(log_type, msg);
		log_mutex.unlock();
	}

	void LogSave::logText(QtMsgType log_type, const QString &msg)
	{
		QString log_line_message = QString("[DataTime:%1] %2").arg(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz")).arg(msg);
		//std::cout << log_line_message.toStdString() << std::endl;
		LogChanged(log_type, log_line_message);
	}

	void LogSave::installMessageHandler() 
	{
		qInstallMsgHandler(logMessageHandler); 
    }
}